package leetcode.code1390;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class Solution {
	public int sumFourDivisors(int[] nums) {
		Map<Integer, Integer> map = new HashMap<>();
		for (int num : nums) {
			map.put(num, map.getOrDefault(num, 0) + 1);
		}
		int ans = 0;
		for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
			int num = entry.getKey(), plus = entry.getValue();
			int sum = this.f(num);
			ans += sum * plus;
		}
		return ans;
	}

	private int f(int num) {
		int ans = 0;
		int cnt = 0;
		for (int i = 1; i <= Math.sqrt(num) && cnt <= 4; i++) {
			if ((num % i) == 0) {
				if (i * i == num) {
					return 0;
				}
				cnt += 2;
				ans += i + num / i;
			}
		}
		return cnt == 4 ? ans : 0;
	}
}
